package com.iapplize.gcm.test.server;

import java.io.IOException;

import javax.servlet.http.*;

import com.google.android.gcm.server.*;

@SuppressWarnings("serial")
public class GCM_Send_Message_Servlet extends HttpServlet {

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String regId = req.getParameter("regId");
		String messageIn = req.getParameter("message");
		
		if(messageIn.equalsIgnoreCase("")){
			messageIn = "Test From Android OK !!!";
		}

		Sender sender = new Sender("yor key");

		Message message = new Message.Builder().addData("message", messageIn)
				.build();

		Result result = sender.send(message, regId, 5);

		if (result.getMessageId() != null) {

			String canonicalRegId = result.getCanonicalRegistrationId();
			if (canonicalRegId != null) {
				// same device has more than on registration ID: update
				// database
			}
		} else {

			String error = result.getErrorCodeName();
			if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
				// application has been removed from device - unregister
				// database
			}
		}

		resp.setContentType("text/plain");
		resp.getWriter().println("regId : " + regId);
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/plain");
		resp.getWriter().println("GCM Server");
	}
}
